<template>
  <div class="login-container">
    <!-- 左侧装饰区域 -->
    <div class="decorative-panel">
      <div class="branding">
        <h1 class="system-name">言㐱陪诊系统</h1>
        <p class="slogan">专业医疗陪伴服务</p>
      </div>
      <div class="decorative-image">
        <div class="gradient-overlay"></div>
      </div>
    </div>
    <!-- 登录表单区域 -->
    <div class="form-panel">
      <div class="form-header">
        <h2 class="welcome-text">欢迎回来</h2>
        <p class="sub-title">请登录您的账号</p>
      </div>
      <el-form
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          label-position="top"
          class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              class="custom-input"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              class="custom-input"
          />
        </el-form-item>
        <el-button
            type="primary"
            class="login-btn"
            @click="handleLogin"
            :loading="loading"
        >
          {{ loading ? '登录中...' : '立即登录' }}
        </el-button>
        <div class="additional-actions">
          <a href="#" @click.prevent="forget" class="link">忘记密码?</a>
          <span class="divider">|</span>
          <a href="#" @click.prevent="customer_click" class="link">立即注册</a>
        </div>
      </el-form>
    </div>
  </div>

  <!-- 模态框 -->
  <el-dialog v-model="dialogFormVisible" title="言㐱陪诊 - 添加账户" width="500">
    <el-form :model="form" :rules="rules" ref="formRef" label-position="right" label-width="auto">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="权限" prop="user_permission">
        <el-radio-group v-model="form.user_permission">
          <el-radio label="customer">客户</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="患者ID" prop="patient_id">
        <el-input v-model="form.patient_id" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div>护士请联系管理员操作账号</div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="!isEdit" type="primary" @click="handleAdd">新增</el-button>
        <el-button v-else type="primary" @click="handleEdit">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import { User, Lock } from '@element-plus/icons-vue';
import { mapActions } from 'vuex';

export default {
  data() {
    return {
      dialogFormVisible: false,
      isEdit: false,
      form: {
        user_id: null,
        username: '',
        password: '',
        user_permission: 'customer',
        patient_id: '',
        escort_id: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        user_permission: [
          { required: true, message: '请选择权限', trigger: 'change' }
        ]
      },
      loading: false,
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }
        ],
      },
    };
  },
  methods: {
    ...mapActions(['loginSuccess']),
    forget() {
      ElMessage({
        message: "账号问题,请联系客服Tel:13512341234",
        type: "error",
      });
    },
    customer_click() {
      this.showAddDialog();
    },
    async handleLogin() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.post("/api/wu_vue_2_test/User/validate", this.loginForm);
            if (res.data.code === 200) {
              // 登录成功，存储用户信息到 localStorage
              localStorage.setItem('user', JSON.stringify(res.data.data));
              // 调用 Vuex 的 action 存储用户 id
              await this.loginSuccess(res.data.data.user_id);
              console.log(66666666666666666666666666666666666666666);
              console.log(this.loginSuccess);
              console.log(666666666666666665555555555555666666666);
              console.log(res.data.data.user_id);
              console.log(6666666666666666655555000005555666666666);
              ElMessage({
                message: "登录成功",
                type: "success",
              });
              // 根据用户权限进行页面跳转
              if (res.data.data.user_permission === "customer") {
                this.$router.push("/customer/home");
              } else if (res.data.data.user_permission === "escort") {
                this.$router.push("/escort/home");
              } else if (res.data.data.user_permission === "root") {
                this.$router.push("/root");
              }
            } else {
              ElMessage({
                message: res.data.msg,
                type: "error",
              });
            }
          } catch (error) {
            console.error("登录失败:", error);
            ElMessage({
              message: "登录失败，请稍后重试",
              type: "error",
            });
          }
        } else {
          console.log("表单验证不通过");
          return false;
        }
      });
    },
    // 2. 添加新数据
    async handleAdd() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            console.log(this.form);
            const res = await axios.post('/api/wu_vue_2_test/User/add', this.form);
            console.log(res);
            this.dialogFormVisible = false;
            await this.getTableData();
            this.showMsg(res);
          } catch (error) {
            console.error('添加数据失败,被占用或网络不佳:', error);
            ElMessage({
              message: '添加数据失败,被占用或网络不佳，请稍后重试',
              type: 'error',
              plain: true
            });
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    },
    // 显示添加新数据对话框
    showAddDialog() {
      this.isEdit = false;
      this.dialogFormVisible = true;
      this.resetForm();
    },
    // 重置表单
    resetForm() {
      this.form = {
        username: '',
        password: '',
        user_permission: 'customer',
        patient_id: '',
        escort_id: ''
      };
    },
    // 显示操作结果消息
    showMsg(res) {
      if (res.data.code === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          plain: true
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'error',
          plain: true
        });
      }
    }
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  background: #f8fafc;
}

.decorative-panel {
  flex: 1;
  background: linear-gradient(135deg, #4a90e2 0%, #63b3ff 100%);
  position: relative;
  overflow: hidden;
}

.branding {
  position: absolute;
  top: 40px;
  left: 40px;
  z-index: 2;
  color: white;
}

.system-name {
  font-size: 2.2rem;
  margin-bottom: 8px;
  letter-spacing: 2px;
}

.slogan {
  font-size: 1.2rem;
  opacity: 0.9;
}

.decorative-image {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('https://images.unsplash.com/photo-1586773860418-d37222d8fce3?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80') center/cover;
}

.gradient-overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(to top, rgba(74, 144, 226, 0.8), rgba(74, 144, 226, 0.4));
}

.form-panel {
  width: 480px;
  background: white;
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: -4px 0 20px rgba(0,0,0,0.05);
}

.form-header {
  margin-bottom: 40px;
}

.welcome-text {
  font-size: 2rem;
  color: #2d3748;
  margin-bottom: 8px;
}

.sub-title {
  color: #718096;
  font-size: 0.95rem;
}

.login-form {
  width: 100%;
}

.custom-input {
  margin-bottom: 24px;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 1.1rem;
  letter-spacing: 2px;
  background: linear-gradient(135deg, #4a90e2 0%, #63b3ff 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(74, 144, 226, 0.3);
}

.additional-actions {
  margin-top: 24px;
  text-align: center;
  color: #718096;
}

.link {
  color: #4a90e2;
  text-decoration: none;
  transition: color 0.2s;
}

.link:hover {
  color: #2c5282;
}

.divider {
  margin: 0 12px;
  opacity: 0.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .decorative-panel {
    display: none;
  }

  .form-panel {
    width: 100%;
    padding: 40px 24px;
  }
}
</style>